package uit.mmt02.xuly;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;

import uit.mmt02.doituong.OneMail;


import android.os.Environment;
import android.util.Log;

public class ConvertMessageToList 
{
	
	String tag = "convertLog";
	OneMail om;
	

//	public List<OneMail>convert(Message[]mess)
//	{
//		List<OneMail>list = new ArrayList<OneMail>();
//		int n = mess.length;
//		try {
//			
//			if(n > 0)
//			{
////				for (int i = 0 ; i < n ; i ++)
//				for(int i = n-1; i > n-6; i--)
//				{
//					if (i >=0)
//					{
//						String from = mess[i].getFrom()[0].toString();
//						String date = mess[i].getSentDate().toString();
//						String sub = mess[i].getSubject();
//						String body = "getbody";
//						
//						//class OneMail
//						OneMail om = new OneMail(from, date, sub, body);
//						list.add(om);
//						Log.v(sub, "add " + i);
//					}
//				}
//			}
//			else
//			{
//				
//				Log.v(tag, "Mess trong , List trong");
//			}
//			
//		} catch (Exception e) {
//			// TODO: handle exception
//			Log.v(tag, "loi convert!!!");
//		}
//		return list;
//		
//	}
	
	public List<OneMail>convert2(Message[]mess)
	{
		List<OneMail>list = new ArrayList<OneMail>();
		int n = mess.length;
		try
		{
			for(int i = n-1; i > n-6; i--)
			{
				if (i >=0)
				{
					OneMail om1 = get1mail(mess, i);
					list.add(om1);
				}
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "loi conver 2");
		}
		return list;
	}
	public List<OneMail>convert(String table_username)
	{
		
		
		return null;
		
	}
	
	
	public OneMail get1mail(Message[] mess, int i) {
		om = new OneMail();

		try {
			om.setDateSend(mess[i].getSentDate().toString());
			om.setSub(mess[i].getSubject());
			om.setFrom(mess[i].getFrom()[0].toString());

			Boolean flag_attachment = false;
			Object content = mess[i].getContent();
			if (content instanceof Multipart) {
				flag_attachment = true;
				handleMultipart((Multipart) content);
			} else {
				flag_attachment = false;				
				handlepart(mess[i]);
			}
			om.setFlagAttach(flag_attachment);
			//Log.i(tag, mess);
			//set co ma hoa va voice // update sau
			om.setFlagEncrypt(true);
			om.setFlagVoice(true);

		} catch (Exception e) {
			// TODO: handle exception
			Log.i(tag, "Loi lay 1 GMAIL mail");
		}
		return om;
	}
	
	@SuppressWarnings("static-access")
	public void handleMultipart(Multipart content) throws Exception {

		Part[] parts =  new Part[content.getCount() - 1];
		Part part;
		int j=0;
		for (int i = 0; i < content.getCount(); i++) {
			//handlepart(content.getBodyPart(i));
			part = content.getBodyPart(i);
			if(part.getDisposition()==null){
				handlepart(part);
			}else if(part.getDisposition().equalsIgnoreCase(part.ATTACHMENT)){
				parts[j] = part;
				j++;
			}
		}
		om.set_attach_parts(parts);

		Log.i("So Attach", Integer.toString(content.getCount() - 1));
		Log.i("max j", Integer.toString(j-1));
		
	}
	
	@SuppressWarnings("static-access")
	public void handlepart(Part part) throws Exception {

		try {
			String disposition = part.getDisposition();
			String contenttype = part.getContentType();
			String messbody = "";
			if(disposition ==null){
				if(contenttype.length() >= 10 && contenttype.toLowerCase().substring(0, 10).equals("text/plain")){
					
					//part.writeTo(System.out);
					BufferedReader bf=new BufferedReader(new InputStreamReader(part.getInputStream()));
					String read;
					while((read = bf.readLine())!=null){
						messbody = messbody+read;
					}
					om.setBody(messbody);
//					Log.i(tag, "message body");
//					Log.i("BODY GMAIL", messbody);
					//part.writeTo(System.out);	
				}else{
					
					BufferedReader bf=new BufferedReader(new InputStreamReader(part.getInputStream()));
					String read;
					while((read = bf.readLine())!=null){
						messbody = messbody+read+"\n";
					}
					om.setBody(messbody);
//					Log.i(tag, "message body");
//					Log.i("BODYGMAIL", messbody);
					//part.writeTo(System.out);
				}
			}else if(disposition.equalsIgnoreCase(part.ATTACHMENT)){
				System.out.println("<<<<----------Attachment: "+part.getFileName()+" : "+contenttype);
				
					savefile(part.getFileName(),part.getInputStream());

				
			}else if(disposition.equalsIgnoreCase(part.INLINE)){
				System.out.println("<<<<<-----------Inline: "+part.getFileName()+" : "+contenttype);
				savefile(part.getFileName(),part.getInputStream());
			}else System.out.println("<<<<<-----------Other: "+disposition);
		} catch (Exception e) {
			Log.i("GMAIL", "Error");
		}
		

	}
	
	public void savefile(String fileName, InputStream inputStream)
			throws Exception {

		try{
			if(fileName==null){
				fileName = File.createTempFile("xxx", ".out").getName();
			}
			File savedir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir");
			savedir.mkdirs();
			File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir",fileName);
			for(int i=0;file.exists();i++){
				savedir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir/"+fileName+i);
				savedir.mkdirs();
				file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/downloaddir/"+fileName+i,fileName);
			}
			
				BufferedOutputStream bufferOUT = new BufferedOutputStream(
						new FileOutputStream(file));

				BufferedInputStream bufferIN = new BufferedInputStream(inputStream);

				int abyte;
				while ((abyte = bufferIN.read()) != -1) {
					bufferOUT.write(abyte);
				}

				bufferOUT.flush();
				bufferOUT.close();
				bufferIN.close();
			} catch (Exception e) {
				Log.i(tag, "ERROR GET ATTACHMET" + e);
			}
	}
	
	

}
